package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备信息表Service业务层处理
 * 
 * @author zhx
 * @date 2025-05-25
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备信息表
     * 
     * @param id 设备信息表主键
     * @return 设备信息表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备信息表列表
     * 
     * @param device 设备信息表
     * @return 设备信息表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备信息表
     * 
     * @param device 设备信息表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备信息表
     * 
     * @param  设备信息表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDevice(DeviceDto dto)
    {
        // 根据id从数据库中查询设备信息
        Device device = this.lambdaQuery().eq(Device::getId, dto.getId()).one();
        String deviceId = device.getIotId();

        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceId);
        UpdateDevice body = new UpdateDevice();

        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        body.withAuthInfo(authInfobody);
        // String deviceJsonStr = JSON.toJSONString(dto);
        body.withExtensionInfo(dto);
        String deviceDescription = dto.getDeviceDescription();
        body.withDescription(deviceDescription);
        body.withDeviceName(dto.getDeviceName());
        log.info("更新数据body:{}",JSON.toJSONString(body));
        request.withBody(body);

        Device device1 = new Device();
        BeanUtils.copyProperties(dto,device1);
        device1.setNickname(dto.getRegisterDeviceRequest().getNickname());
        boolean b = this.updateById(device1);
        if (!b){
            throw new BaseException("更新设备数据失败");
        }
        if (device1.getLocationType() == 0){
            //随身设备,强制更新PhysicalLocationType,和DeviceDescription为null
            this.update(Wrappers.<Device>lambdaUpdate()
                    .eq(Device::getIotId,device1.getIotId())
                    .set(Device::getPhysicalLocationType,null)
                    .set(Device::getDeviceDescription,null)
            );
        }

        UpdateDeviceResponse response = client.updateDevice(request);
        if (response == null || response.getHttpStatusCode() != 200){
            throw new BaseException("更新设备数据失败");
        }
    }

    /**
     * 批量删除设备信息表
     * 
     * @param ids 需要删除的设备信息表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息表信息
     * 
     * @param id 设备信息表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IoTDAClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        //对接华为云api,获取产品列表
        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if (response == null || response.getHttpStatusCode()!=200){
            throw new BaseException("同步产品列表失败");
        }

        //将获取到的产品列表转为JSON字符串存入Redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSON.toJSONString(response.getProducts()));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从Redis中查询产品列表JSON字符串
        String productListJSON = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StringUtils.isBlank(productListJSON)){
            throw new BaseException("查询产品列表失败");
        }

        //将JSON字符串转成产品列表
        List<ProductSummary> productList = JSONUtil.toList(productListJSON, ProductSummary.class);

        //遍历产品列表,转成前段需要的数据类型
        List<ProductVo> productVoList = productList.stream().map(x -> {
            return ProductVo.builder().productName(x.getName()).productKey(x.getProductId()).build();
        }).collect(Collectors.toList());

        return productVoList;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(DeviceDto dto) {
        //1. 判断设备名称是否重复
        Long countDevice = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (countDevice > 0){
            throw new BaseException("设备重名");
        }

        //2. 判断设备标识是否重复
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        Long countNodeId = this.lambdaQuery().eq(Device::getNodeId, nodeId).count();
        if (countNodeId > 0){
            throw new BaseException("设备标识重复");
        }

        //3. 判断同一位置是否绑定了相同的产品
        Long countLocation = this.lambdaQuery().eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .count();
        if (countLocation > 0){
            throw new BaseException("该位置已绑定过同类型产品");
        }

        //4. 调用IoT接口注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setNodeId(nodeId); //设备标识码 (必填参数)
        body.setProductId(dto.getProductKey()); //设备关联的产品Id (产品唯一标识)
        body.setDeviceName(dto.getDeviceName()); //设备名称
        String description = dto.getRegisterDeviceRequest().getNickname();
        body.setDescription(description); //设备描述 (设备备注)

        String secret = IdUtil.fastSimpleUUID(); //设备秘钥 (UUID的唯一值)
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret); //设备秘钥
        body.setAuthInfo(authInfo);

        request.withBody(body);

        //发起注册设备请求,得到响应结果
        AddDeviceResponse response = client.addDevice(request);
        if (response == null || response.getHttpStatusCode() != 201){
            throw new BaseException("调用IoT接口注册设备失败");
        }

        //5. 解析响应结果
        String iotId = response.getDeviceId(); //物联网设备唯一id

        //6. 新增设备到表中
        Device device = new Device();
        BeanUtils.copyProperties(dto,device);
        device.setIotId(iotId); //物联网设备唯一id
        device.setSecret(secret); //设备秘钥
        device.setNodeId(nodeId); //设备标识符
        device.setDeviceDescription(dto.getDeviceDescription()); //设备描述
        device.setNickname(description); //设备备注
        String productName = getProductName(dto.getProductKey());
        device.setProductName(productName); //产品名
        boolean result = this.save(device);
        if (!result){
            throw new BaseException("新增设备失败");
        }
    }

    private String getProductName(String productKey) {
        //1. 查询Redis产品列表的JSON字符串
        String productListJSON = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);

        //2. 解析JSON字符串为产品列表
        List<ProductSummary> productList = JSONUtil.toList(productListJSON, ProductSummary.class);

        //3. 筛选出列表中同名产品id的产品对象
        ProductSummary product = productList.stream().filter(x -> x.getProductId().equals(productKey)).findFirst().get();

        //4. 获取该筛选到的产品对象的产品名
        if (product != null){
            return product.getName();
        }
        return null;
    }

    @Autowired
    private ISysUserService userService;

    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    /**
     * 获取设备详细信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //1. 判断设备是否存在
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device == null){
            throw new BaseException("设备不存在");
        }

        //2. 拷贝Device对象为DeviceDetailvo对象
        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(device,vo);

        //3. 补充设置一些属性值
        vo.setDeviceSecret(device.getSecret()); //设备秘钥
        vo.setGmtCreate(device.getCreateTime()); //设备创建时间

        SysUser sysUser = userService.selectUserById(Long.valueOf(device.getCreateBy()));
        vo.setCreator(sysUser.getUserName()); //创建人
        vo.setRegion(huaWeiIotConfigProperties.getRegionId()); //区域id

        //4. 调用华为云IoT接口获取设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId); //设备id
        ShowDeviceResponse response = client.showDevice(request);
        if (response == null || response.getHttpStatusCode() != 200){
            throw new BaseException("调用华为云IoT接口获取设备详情失败");
        }

        //5. 补充设置一些属性值
        vo.setDeviceStatus(response.getStatus());
        vo.setStatus(response.getStatus()); //设备状态 : INACTIVE：设备未激活。 ONLINE：设备在线。OFFLINE：设备离线

        //设备激活时间。格式：yyyy-MM-dd'T'HH:mm:ss.SSS'Z' ，如2015-12-12T12:12:122Z。这种时间是国际标准时区的时间，比东八区（亚洲/上海）早8小时
        String activeTime = response.getActiveTime();
        if (!StringUtils.isBlank(activeTime)){
            //转换为东八区的时间,且类型为localdateTime
            LocalDateTime gmtActive = OffsetDateTime.parse(activeTime).atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            vo.setGmtActive(gmtActive);
        }
        vo.setFirmwareVersion(response.getFwVersion());

        return vo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param productKey
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //1. 调用华为云IoT接口查询产品详情
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response == null || response.getHttpStatusCode() != 200){
            throw new BaseException("调用华为云IoT接口查询产品详情失败");
        }

        //2. 解析响应结果
        List<ServiceCapability> serviceCapabilityList = response.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilityList)){
            throw new BaseException("没有查询到物模型数据");
        }
        ServiceCapability serviceCapability = serviceCapabilityList.get(0);

        //3. 数据类型转换
        JSONObject jsonObject = JSONUtil.parseObj(serviceCapability);

        return jsonObject;
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param deviceName
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName) {
        //1. 判断设备是否存在
        Device device = this.lambdaQuery().eq(Device::getDeviceName, deviceName).select(Device::getIotId).one();
        if (device == null){
            throw new BaseException("设备不存在");
        }
        String deviceId = device.getIotId(); //获取设备id

        //2. 调用华为云IoT接口查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(deviceId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response == null || response.getHttpStatusCode() != 200){
            throw new BaseException("调用华为云IoT接口查询设备影子数据失败");
        }

        //3. 解析响应结果数据,封装map的数据
        List<DeviceShadowData> shadowDataList = response.getShadow();
        if (CollUtil.isEmpty(shadowDataList)){
            throw new BaseException("调用华为云IoT接口查询设备影子数据为空");
        }
        DeviceShadowData shadowData = shadowDataList.get(0);
        DeviceShadowProperties reported = shadowData.getReported();
        //事件操作时间，格式：yyyyMMdd'T'HHmmss'Z'，如20151212T121212Z。该值是国际标准时间，比东八区早八小时
        String eventTimeStr = reported.getEventTime();
        //转为东八区时间
        LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        JSONObject properties = JSONUtil.parseObj(reported.getProperties());
        List<Map<String,Object>> propertyStatusInfo  = new ArrayList<>();
        properties.forEach((k,v) -> {
            //封装属性对象
            Map<String,Object> propertyMap = new HashMap<>();
            propertyMap.put("identifier", k);
            propertyMap.put("name",k);
            propertyMap.put("value",v);
            propertyMap.put("time",eventTime);
            propertyStatusInfo.add(propertyMap);
        });

        //4. 返回map数据
        Map<String,Object> resultMap = new HashMap<>();

        Map<String,Object> propertyStatusInfoMap = new HashMap<>();
        propertyStatusInfoMap.put("propertyStatusInfo",propertyStatusInfo);

        resultMap.put("list",propertyStatusInfoMap);

        return resultMap;
    }

    @Autowired
    private IDeviceDataService deviceDataService;

    /**
     * 删除设备信息
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDeviceByIoTId(DeviceDto dto) {
        String iotId = dto.getIotId();

        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        //删除数据库设备信息
        boolean result = this.removeById(device);
        if (!result){
            throw new BaseException("删除数据库设备信息失败");
        }
        //删除device_data表中对应数据
        List<DeviceData> deviceDataList = deviceDataService.lambdaQuery().eq(DeviceData::getIotId, iotId).list();
        if (CollUtil.isNotEmpty(deviceDataList)){
            deviceDataList.forEach(x->{
                deviceDataService.removeById(x.getId());
            });
        }

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        //删除华为IoT云平台的设备
        try {
            DeleteDeviceResponse response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("删除IoT云平台设备失败");
        }
    }
}
